package com.me.study.concurrent.thread;

/**
 * 1，如果线程被调用了 Object.wait()/Object.wait(long), 或者调用了 sleep(long)/join()/join(long) 方法，
 * 会抛出 InterruptedException，并且中断标记位会被清除
 * 2，thread.interrupt()         设置中断标记
 *    thread.isInterrupted()     获取线程的中断标记
 *    Thread.interrupted()       获取线程的中断标记，并清除
 *
 * @author ME
 * @date   2019/3/5 16:52
 */
public class TestInterrupt {

    public static void main(String[] args) {
        // sleepThread睡眠1000ms
        final Thread sleepThread = new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                super.run();
            }
        };
        // busyThread一直执行死循环
        Thread busyThread = new Thread() {
            @Override
            public void run() {
                while (true) ;
            }
        };

        sleepThread.start();
        busyThread.start();
        sleepThread.interrupt();
        busyThread.interrupt();
        while (sleepThread.isInterrupted()) {
            // 因为抛出 InterruptedException 异常才会清除中断标记，
            // 所以死循环保证先异常才能看到清除结果
        }
        System.out.println("sleepThread isInterrupted: " + sleepThread.isInterrupted());// false
        System.out.println("busyThread isInterrupted: " + busyThread.isInterrupted());// true

        System.out.println();
        System.out.println("当前线程 isInterrupted: " + Thread.currentThread().isInterrupted());// false
        Thread.currentThread().interrupt();
        System.out.println("当前线程 isInterrupted: " + Thread.currentThread().isInterrupted());// true, 并且清除标记
        Thread.interrupted();
        System.out.println("当前线程 isInterrupted: " + Thread.currentThread().isInterrupted());// false
    }

}
